package com.ai.platform.core.controller;

import com.ai.platform.model.dto.Output;
import com.ai.platform.core.constant.IConstants;
import com.ai.platform.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yeyingsheng on 2018/5/21.
 * Controller异常拦截
 */
@ControllerAdvice
public class ExceptionHandlerController {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Output exception(HttpServletRequest request, Exception exception) {
         logger.error("exception : " + exception);
         Output output=new Output();
         long startTime=System.currentTimeMillis();
         if(exception instanceof BindException){
             BindException ex= (BindException) exception;
             //参数校验异常
             BindingResult result = ex.getBindingResult();
             final List<FieldError> fieldErrors = result.getFieldErrors();
             List<Map<String,String>> errorList=new ArrayList<>();
             Map<String,String> map;
             StringBuffer stringBuffer=new StringBuffer();
             for (FieldError error : fieldErrors) {
                 map=new HashMap<>();
                 map.put(error.getField(),error.getDefaultMessage());
                 errorList.add(map);
                 stringBuffer.append(error.getDefaultMessage()+"\n");
             }
             output.setCode(IConstants.FIELD_VALID_ERROR);
             output.setData(errorList);
             output.setMsg(stringBuffer.toString());
         }else if(exception instanceof BusinessException){
             BusinessException businessException= (BusinessException) exception;
             //业务异常
             output.setCode(IConstants.BUSINESS_ERROR);
             output.setMsg(businessException.getMessage());
         }else{
             //其他异常
             output.setCode(IConstants.UNKNOWN_ERROR);
             output.setMsg(exception.getMessage());
         }
         long endTime=System.currentTimeMillis();
         long cost=endTime-startTime;
         output.setStartTime(startTime);
         output.setEndTime(endTime);
         output.setCost(cost);
         return output;
    }
}
